package utils

import (
	"regexp"
	"strconv"
	"strings"
)

// ValidMobile 校验手机号
func ValidMobile(mobile string) bool {
	res := regexp.MustCompile(`^1[3456789]\d{9}$`)
	return res.MatchString(mobile)
}

// ValidUserName 校验用户名
func ValidUserName(userName string) bool {
	res := regexp.MustCompile(`^[\u4e00-\u9fa5a-zA-Z0-9_]{1,50}$`)
	return res.MatchString(userName)
}

// ValidEmail 校验邮箱
func ValidEmail(email string) bool {
	res := regexp.MustCompile(`^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$`)
	return res.MatchString(email)
}

// ValidIDCard 检查身份证号
func ValidIDCard(idNumber string) bool {
	reg, _ := regexp.Compile(`^\d{17}[\dX]$`)
	if !reg.MatchString(idNumber) {
		return false
	}

	weight := [17]int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
	check := [11]interface{}{1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2}
	sum := 0
	for i := 0; i < 17; i++ {
		itemInt, err := strconv.Atoi(idNumber[i : i+1])
		if err != nil {
			return false
		}
		sum += weight[i] * itemInt
	}

	mod := sum % 11
	if mod == 2 {
		if strings.ToUpper(idNumber[17:18]) != check[sum%11].(string) {
			return false
		}
	} else {
		itemInt, err := strconv.Atoi(idNumber[17:18])
		if err != nil {
			return false
		}

		if check[sum%11].(int) != itemInt {
			return false
		}
	}

	return true

}
